<template>
  <div class="admin-order-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>订单管理</h2>
          <!-- <el-button type="primary" @click="handleAddOrder">新建订单</el-button> -->
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.order_number" placeholder="请输入订单编号" @input="handleSearch" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" filterable @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="待付款" value="pending" />
            <el-option label="已付款" value="paid" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 订单列表 -->
      <el-table :data="orders" style="width: 100%">
        <el-table-column prop="order_number" label="订单编号" width="180" />
        <el-table-column prop="customer_name" label="客户名称" width="120" />
        <el-table-column prop="address" label="配送地址" min-width="200" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="total_amount" label="订单金额" width="120">
          <template #default="{ row }">
            ¥{{ row.total_amount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payment_time" label="下单时间" width="180">
          <template #default="{ row }">
            <span v-if="row.payment_time && !isNaN(new Date(row.payment_time).getTime())">
              {{ new Date(row.payment_time).toLocaleString() }}
            </span>
            <span v-else style="color: #ccc;">--</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="success" link @click="handleViewDetails(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新建订单' : '编辑订单'"
      width="50%"
    >
      <el-form :model="orderForm" label-width="100px">
        <el-form-item label="客户名称">
          <el-input v-model="orderForm.customer_name" />
        </el-form-item>
        <el-form-item label="配送地址">
          <el-input v-model="orderForm.address" type="textarea" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="orderForm.phone" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="orderForm.status" filterable>
            <el-option label="待付款" value="pending" />
            <el-option label="已付款" value="paid" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <template v-if="orderDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ orderDetail.order_number }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ orderDetail.customer_name }}</el-descriptions-item>
          <el-descriptions-item label="配送地址">{{ orderDetail.address }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ orderDetail.phone }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ orderDetail.total_amount }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(orderDetail.status)">
              {{ getStatusText(orderDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">
            {{ new Date(orderDetail.created_at).toLocaleString() }}
          </el-descriptions-item>
          <el-descriptions-item label="备注">{{ orderDetail.remark }}</el-descriptions-item>
        </el-descriptions>
        <div style="margin: 20px 0 10px 0; font-weight: bold;">商品明细</div>
        <el-table :data="orderDetail.items" size="small" border>
          <el-table-column prop="product_name" label="商品名称" />
          <el-table-column prop="quantity" label="数量" />
          <el-table-column prop="unit" label="单位" />
          <el-table-column prop="unit_price" label="单价" >
            <template #default="{ row }">¥{{ row.unit_price }}</template>
          </el-table-column>
          <el-table-column prop="total_price" label="小计" >
            <template #default="{ row }">¥{{ row.total_price }}</template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { getToken } from '@/utils/auth'

// axios请求拦截器，自动加token和Content-Type
axios.interceptors.request.use(config => {
  const token = getToken()
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`
  }
  config.headers['Content-Type'] = 'application/json'
  return config
})

// 搜索表单
const searchForm = ref({
  order_number: '',
  status: ''
})

// 订单列表数据
const orders = ref([])
const ordersAll = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const orderForm = ref({
  items_data: [], // [{product: 1, quantity: 2, unit_price: 10.0}]
  shipping_address: '',
  contact_phone: '',
  remark: ''
})

const detailDialogVisible = ref(false)
const orderDetail = ref(null)

// 获取状态样式
const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',    // 待付款
    paid: 'info',         // 已付款
    shipped: 'primary',   // 已发货
    completed: 'success', // 已完成
    cancelled: 'danger'   // 已取消
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return textMap[status] || '未知'
}

// 获取全部订单
const fetchOrders = async () => {
  try {
    const response = await axios.get('/api/orders/', {
      params: {
        page: 1,
        page_size: 1000 // 拉取全部订单
      }
    })
    const data = response.data.data
    ordersAll.value = data.items || []
    filterOrders() // 初始渲染
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  }
}

// 本地过滤
const filterOrders = () => {
  let filtered = ordersAll.value
  if (searchForm.value.order_number) {
    filtered = filtered.filter(order =>
      order.order_number && order.order_number.includes(searchForm.value.order_number)
    )
  }
  if (searchForm.value.status) {
    filtered = filtered.filter(order => order.status === searchForm.value.status)
  }
  
  // 调整顺序：将已取消的放最后
  filtered = [
    ...filtered.filter(o => o.status !== 'cancelled'),
    ...filtered.filter(o => o.status === 'cancelled')
  ]
  
  // 更新总数
  total.value = filtered.length
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  orders.value = filtered.slice(start, end)
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  filterOrders()
}

// 处理重置
const handleReset = () => {
  searchForm.value = {
    order_number: '',
    status: ''
  }
  currentPage.value = 1
  filterOrders()
}

// 假设有 deliveries 列表可用（如通过 props、全局store或接口获取）
// 新建订单前校验是否已有关联配送任务
const hasDeliveryTask = (orderNumber) => {
  // 这里假设 deliveries 是全局可用的配送任务列表
  if (!window.allDeliveries) return false;
  return window.allDeliveries.some(d => d.order_number === orderNumber)
}

// 处理查看详情
const handleViewDetails = async (row) => {
  try {
    const response = await axios.get(`/api/orders/${row.id}/`)
    orderDetail.value = response.data.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取订单详情失败')
  }
}

// 处理提交
const handleSubmit = async () => {
  try {
    // 新建前校验：订单号是否已有关联配送任务
    if (dialogType.value === 'add' && orderForm.value.order_number) {
      if (hasDeliveryTask(orderForm.value.order_number)) {
        ElMessage.error('该订单已有关联的配送任务，不能重复创建！')
        return
      }
    }
    if (dialogType.value === 'add') {
      await axios.post('/api/orders/', orderForm.value)
      ElMessage.success('新建成功')
    } else {
      await axios.put(`/api/orders/${orderForm.value.id}/status/`, {
        status: orderForm.value.status
      })
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    fetchOrders()
  } catch (error) {
    if (error.response && error.response.status === 400 && error.response.data) {
      const msg = Object.values(error.response.data).flat().join('; ')
      ElMessage.error((dialogType.value === 'add' ? '新建失败: ' : '更新失败: ') + msg)
    } else if (error.response && error.response.status === 500) {
      ElMessage.error('后端服务异常，请联系管理员修复接口权限配置')
    } else {
      ElMessage.error((dialogType.value === 'add' ? '新建失败: ' : '更新失败: ') + error.message)
    }
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  filterOrders()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  filterOrders()
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.admin-order-management {
  padding: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 